package demo

import (
	"context"
	"fmt"
	"time"

	etcdclient "go.etcd.io/etcd/client/v3"
)

func init() {
	Register("EtcdValue", func() Service {
		return new(EtcdValue)
	})

	fmt.Println("EtcdValue registered")
}

type EtcdValue struct{}

func (ev *EtcdValue) Exec() {
	client, err := etcdclient.New(etcdclient.Config{
		Endpoints:   []string{"http://localhost:2379"},
		DialTimeout: 5 * time.Second,
	})

	if err != nil {
		fmt.Printf("failed to etcd_value: %v\n", err)
	}
	defer client.Close()

	// put
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err = client.Put(ctx, "q1mi", "dsb")
	cancel()
	if err != nil {
		fmt.Printf("put to etcd failed, err:%v\n", err)
		return
	}

	// get
	ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	resp, err := client.Get(ctx, "q1mi", etcdclient.WithSerializable()) // 默认线性度，串行读可通过降低一致性来降低读取耗时
	cancel()
	if err != nil {
		fmt.Printf("get from etcd failed, err:%v\n", err)
		return
	}
	for _, ev := range resp.Kvs {
		fmt.Printf("%s:%s\n", ev.Key, ev.Value)
	}
}
